let axios = require('axios');
let fs = require('fs');
let path = require('path');
let readmePath = path.join(path.join(__dirname, 'README.md'));
let pathDoc = `/ztjy-technology/docs`;

// copy文件
function copyFile(fromPath, toPath) {
  try {
    fs.writeFileSync(toPath, fs.readFileSync(fromPath));
  } catch (e) {
    console.error(e);
  }
}

/**
 *
 * @param forceUpdate 是否强制更新 默认 false
 * @returns {Promise<[]>} .catch 进行错误的处理
 */
async function generatorNavAndSlider(forceUpdate = false) {

  let text = fs.readFileSync(readmePath, 'utf-8');
  let textDoc = fs.readFileSync(path.join(__dirname, `${pathDoc}/index/README.md`), 'utf-8');
  if (!forceUpdate && textDoc === text) {
    console.log('无更新');
    return
  }
  let filterNAndR = text.split('\n').filter(item => item !== '\r').map(item => item.slice(0));
  let newArr = [];
  let prePath = '';
  let sidebar = {};
  // 只有改动才重新生成
  for (let i = 0; i < filterNAndR.length; i++) {
    let item = filterNAndR[i];
    if (item.startsWith('##')) {
      item = item.slice(3);
      newArr.push({text: item});
      prePath = await (await axios({url: `https://gitee.com/search/translate`, params: {q: item}})).data.result;
      console.log(item, prePath);
      if (!fs.existsSync(path.join(__dirname, `${pathDoc}/${prePath}`))) {
        fs.mkdirSync(path.join(__dirname, `${pathDoc}/${prePath}`));
      }
    } else if (item.startsWith('-')) {
      item = item.slice(6);
      let newItem;
      if (item.startsWith('[')) {
        item = item.split(' ')[0].slice(1);
        newItem = item;
        console.log('已分享知识点', item);
      } else {
        newItem = item.split(' ')[0]
      }
      if (!newArr[newArr.length - 1]['items']) {
        newArr[newArr.length - 1]['items'] = [];
      }
      let link = await axios({
        url: `https://gitee.com/search/translate`,
        params: {q: newItem}
      });
      link = '/' + prePath + '/' + link.data.result;
      if (!fs.existsSync(path.join(__dirname, `${pathDoc}${link}`))) {
        fs.mkdirSync(path.join(__dirname, `${pathDoc}${link}`));
        console.log(`根据-${newItem}-翻译并创建${pathDoc}${link}`);
      }
      if (!fs.existsSync(path.join(__dirname, `${pathDoc}${link}/README.md`))) {
        fs.writeFileSync(path.join(__dirname, `${pathDoc}${link}/README.md`), `# ${newItem}`);
        console.log(`根据-${newItem}-翻译并创建${pathDoc}${link}/README.md`);
      }

      //生成sidebar
      sidebar[`${link}/`] = [
        {
          title: item,
          collapsable: true,
          children: [
            link + '/'
          ],
        }
      ];
      newArr[newArr.length - 1]['items'].push({
        text: item, link: link + '/'
      });
    }
  }
  fs.writeFileSync(path.join(__dirname, 'ztjy-technology/docs/guide/nav.js'), 'module.exports = ' + JSON.stringify(newArr));
  fs.writeFileSync(path.join(__dirname, 'ztjy-technology/docs/guide/sidebar.js'), 'module.exports = ' + JSON.stringify(sidebar));
  return newArr;
}

// promise 多并发

//对async和await错误的处理
generatorNavAndSlider(false).catch(r => console.error(r));

copyFile(
  readmePath,
  path.join(__dirname, 'ztjy-technology/docs/index/README.md')
);
